//
//  FirstSearchViewController.m
//  marrymarry
//
//  Created by lsj on 16/9/12.
//  Copyright © 2016年 cf. All rights reserved.
//
static NSString * FirstTabCellID = @"FirstTabTableViewCell";
#import "FirstSearchViewController.h"
#import "FirstTabTableViewCell.h"
#import "ThirdMineViewController.h"
#import "SendGiftViewController.h"
#import "HomeModel.h"
#import "TopUpViewController.h"
@interface FirstSearchViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UIWindow * window;
    int pageNum;
    YiRefreshHeader *refreshHeader;
    YiRefreshFooter *refreshFooter;
    int  isloadTF;
    BOOL isDraggingDown;
    int total;
    NSString * _otherID;
    int  _endCount;
    BOOL _isClose;
    NSString * _canpay;
    
}
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UIView *backGroundGrayView;
@property (strong , nonatomic) NSMutableArray * dataArry;
@property (strong , nonatomic) NSMutableArray * heartArry;
@property (strong , nonatomic) HomeModel * myModel ;
@property (nonatomic,strong) CFinfoModel * model;
@end

@implementation FirstSearchViewController

///心动数组
-(NSMutableArray *)heartArry
{
    if (!_heartArry) {
        _heartArry = [NSMutableArray new];
        
    }
    return _heartArry;
}

-(NSMutableArray *)dataArry
{
    if (!_dataArry) {
        _dataArry = [NSMutableArray new];
      
    }
    return _dataArry;
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.hidden = NO;
    [super viewWillAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor redColor];
    self.title = @"你来约";
    self.view.backgroundColor = RGB(245, 245, 247);
    self.myTableView.separatorStyle = NO;
    self.myTableView.frame = CGRectMake(0,0,ScreenWidth, ScreenHeight);
    self.model = [CFinfoModel new];
    self.myModel = [HomeModel new];
    [self setUI];
    
    [self CanPayWithURL];
}

-(void)CanPayWithURL
{
    
    [[LJFNetworkingManager shareManager] POST:CANPAY_URL parameters:nil success:^(id returnData, int code, NSString *msg) {
        NSLog(@"%@",msg);
        NSLog(@"returnData  ===== %@",returnData);
        NSArray * myArry = returnData;
        if (myArry.count>0) {
            _canpay = [NSString stringWithFormat:@"%d",[returnData[2][@"myvalue"] intValue]];
            [Tools syncNSUserDeafaultsByKey:@"canpay" withValue:_canpay];

        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    } showHUD:self.view];

}
-(void)setUI
{
    pageNum = 0;
    __block FirstSearchViewController *blockSelf =self;
    
    // YiRefreshHeader  头部刷新按钮的使用
    refreshHeader=[[YiRefreshHeader alloc] init];
    refreshHeader.scrollView=self.myTableView;
    [refreshHeader header];
    typeof(refreshHeader) __weak weakRefreshHeader = refreshHeader;
    refreshHeader.beginRefreshingBlock=^(){
        // 后台执行：
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            sleep(2);
            dispatch_async(dispatch_get_main_queue(), ^{
                typeof(weakRefreshHeader) __strong strongRefreshHeader = weakRefreshHeader;
                // 主线程刷新视图
                pageNum = 1;
                _endCount = 0;
                isDraggingDown = NO;
                [blockSelf loadDataFromNet];
                [strongRefreshHeader endRefreshing];
            });
        });
    };
    
    // 是否在进入该界面的时候就开始进入刷新状态
    [refreshHeader beginRefreshing];
    
    // YiRefreshFooter  底部刷新按钮的使用
    refreshFooter=[[YiRefreshFooter alloc] init];
    refreshFooter.scrollView=self.myTableView;
    [refreshFooter footer];
    typeof(refreshFooter) __weak weakRefreshFooter = refreshFooter;
    
    refreshFooter.beginRefreshingBlock=^(){
        // 后台执行：
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            sleep(2);
            dispatch_async(dispatch_get_main_queue(), ^{
                typeof(weakRefreshFooter) __strong strongRefreshFooter = weakRefreshFooter;
                // 主线程刷新视图
                pageNum = pageNum+1;
                isDraggingDown = YES;
                if (_endCount == 1) {
                    
                }else{
                    [blockSelf loadDataFromNet];
                }
                
                [strongRefreshFooter endRefreshing];
              
            });
        });
    };

}


- (void)loadDataFromNet
{
    ///是否为下拉，是下拉清空数组；
    if (!isDraggingDown) {

        [self.dataArry removeAllObjects];
    }
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:[Tools getValueFromNSUserDefaultsByKey:USERID] forKey:@"id"];
    [dic setObject:[NSString stringWithFormat:@"%d",pageNum] forKey:@"currentPage"];
    [dic setObject:[NSString stringWithFormat:@"%d",3] forKey:@"pageSize"];
    [[LJFNetworkingManager shareManager] POST:HOME_URL parameters:dic success:^(id returnData, int code, NSString *msg)
     {
         if (code == 1)
         {
             
             NSLog(@"returnData ======= %@",returnData);
             NSArray * myArry = [NSArray new];
             myArry= returnData[@"userlist"];
             for (NSDictionary * mydic in myArry) {
                 self.myModel = [HomeModel new];
                 [self.myModel loadDataWithDic:mydic];
                 [self.dataArry addObject:self.myModel];
             }

             self.heartArry = [NSMutableArray arrayWithArray:returnData[@"hearts"]];
             [self.myTableView reloadData];
            
             
         }else
         {
             NSLog(@"msg == %@",msg);
             _endCount = 1;
         }
     } failure:^(NSError *error)
     {
         _endCount = 1;
         
     } showHUD:nil];

    
}



#pragma mark UITableViewDatasource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.dataArry.count>0) {
        return 1;
    }else
    {
        return  0;
    }
    
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return self.dataArry.count;    
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    

    FirstTabTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:FirstTabCellID];
    if (!cell) {
        cell = [[FirstTabTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FirstTabCellID];
        
    }
    if (self.dataArry.count>0) {
        [cell reloadTheCellWithIndexPath:indexPath andArray:self.dataArry andHadHeartArry:self.heartArry];
        self.myModel = self.dataArry[indexPath.row];
        cell.heartBtn.tag = [self.myModel.otherId intValue];
        [cell.heartBtn addTarget:self action:@selector(clickHeart:) forControlEvents:UIControlEventTouchUpInside];
        [cell.giftBtn addTarget:self action:@selector(clickGifts:) forControlEvents:UIControlEventTouchUpInside];
        cell.giftBtn.tag =  [self.myModel.otherId intValue] +100;
        cell.personImgView.clipsToBounds = YES;
        ///全文btn;
        if (_isClose) {
            [cell.allInfoBtn setTitle:@"收起" forState:UIControlStateNormal];
        
        }else{
            [cell.allInfoBtn setTitle:@"展开" forState:UIControlStateNormal];
            
        }
        
        [cell.allInfoBtn addTarget:self action:@selector(OpenTheInfo:) forControlEvents:UIControlEventTouchUpInside];
        cell.RzimgView.userInteractionEnabled = YES;
        UITapGestureRecognizer * addvtap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addv)];
        [cell.RzimgView addGestureRecognizer:addvtap];
        if ([_canpay isEqualToString:@"0"]) {
            cell.giftBtn.hidden =YES;
        }else{
            cell.giftBtn.hidden = NO;
        }
        
    }
   
    cell.backgroundColor = RGB(245, 245, 247);
    return cell;
    
    
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isClose) {
        return ScreenWidth +150;
    }else{
    return ScreenWidth+100;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.myModel = self.dataArry[indexPath.row];
    _otherID = self.myModel.otherId;
    [self requestTheNetWith:nil andURL:OTHERALLINFO_URL andDic:@{@"to":self.myModel.otherId,@"from":[Tools getValueFromNSUserDefaultsByKey:USERID]} andRequestSingStr:@"lookOtherInfoRequest"];
    
}
-(void)addv
{
    UIStoryboard * TopUpSB = [UIStoryboard storyboardWithName:@"TopUpViewController" bundle:nil];
    TopUpViewController * TopUpVC  = [TopUpSB instantiateViewControllerWithIdentifier:@"TopUpViewController"];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:TopUpVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

-(void)OpenTheInfo:(UIButton *)btn
{
    
    if (_isClose) {
        [btn setTitle:@"展开" forState:UIControlStateNormal];
        _isClose = NO;
    }else{
        [btn setTitle:@"收起" forState:UIControlStateNormal];
        _isClose = YES;
    }
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark ---------点击了心动
-(void)clickHeart:(UIButton *)heartBtn
{
    NSString * typeStr ;
    /**  如果心动数组里包含了当前用户id 那么表示等于2 取消心动 否则标识等于1 点亮心动  **/
    if ([self.heartArry containsObject:[NSNumber numberWithInteger:heartBtn.tag]]) {
        [self.heartArry removeObject:[NSNumber numberWithInteger:heartBtn.tag]];
        typeStr = @"2";
        [heartBtn setImage:[UIImage imageNamed:@"heartBtn" ] forState:UIControlStateNormal];
    }else{
        [self.heartArry addObject:[NSNumber numberWithInteger:heartBtn.tag]];
        typeStr = @"1";
        [heartBtn setImage:[UIImage imageNamed:@"heartLight"] forState:UIControlStateNormal];
    }
    [self requestTheNetWith:nil andURL:HEARTCLICK_URL andDic:@{@"from":[Tools getValueFromNSUserDefaultsByKey:USERID],@"to":[NSString stringWithFormat:@"%ld",(long)heartBtn.tag],@"type":typeStr} andRequestSingStr:@"heartRequest"];
}


#pragma mark ----------点击了送礼物
-(void)clickGifts:(UIButton*)giftBtn
{
    UIStoryboard * SGSB =[UIStoryboard storyboardWithName:@"FirstSearchViewController" bundle:nil];
    
    SendGiftViewController * sendGiftVC = [SGSB instantiateViewControllerWithIdentifier:@"SendGiftViewController"];
    sendGiftVC.fromStr = [Tools getValueFromNSUserDefaultsByKey:USERID];
    sendGiftVC.toStr = [NSString stringWithFormat:@"%ld",giftBtn.tag -100];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:sendGiftVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}


#pragma mark --------------网络请求
-(void)requestTheNetWith:(NSArray *)myRequestArry andURL:(NSString *)myurl andDic:(NSDictionary *)myDic andRequestSingStr:(NSString *)SingStr;
{
    if (myRequestArry.count>0) {
        [[LJFNetworkingManager shareManager] POST:myurl upLoadImages:myRequestArry parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            
        } failure:^(NSError *error) {
            NSLog(@"失败");
            
        } showHUD:self.view];
        
    }else
    {
        [[LJFNetworkingManager shareManager] POST:myurl parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            if ([SingStr isEqualToString:@"lookOtherInfoRequest"]) {
                [self.model saveTheOtherBiggestDic:returnData];
                UIStoryboard * otherSB = [UIStoryboard storyboardWithName:@"ThirdMineViewController" bundle:nil];
                ThirdMineViewController * otherVC = [otherSB instantiateViewControllerWithIdentifier:@"ThirdMineViewController"];
                otherVC.otherID = _otherID;
                otherVC.isGoToOther = YES;
                self.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:otherVC animated:YES];
                self.hidesBottomBarWhenPushed = NO;
            }else if ([SingStr isEqualToString:@"heartRequest"]){
                if (code == 1) {
                    NSLog(@"更新ok");
                }
            }
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        } showHUD:self.view];
        
    }
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
